package br.com.naybee.framework.client.componente.gwt.web;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.OptionElement;
import com.google.gwt.dom.client.SelectElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;

public class SelectMultiple extends ComplexPanel implements HasClickHandlers {

	private SelectElement selectElement = DOM.createSelect(true).cast();

	public SelectMultiple() {
		setElement(selectElement);
	}

	public void add(Widget w) {
		Element element = this.selectElement;
		this.add(w, element);
	}

	public void setClassName(String className) {
		selectElement.setClassName(className);
	}

	public String getClassName() {
		return selectElement.getClassName();
	}

	public List<Option> getOptions() {
		List<Option> listOptions = new ArrayList<Option>();
		NodeList<OptionElement> options = selectElement.getOptions();
		for (int i = 0; i < options.getLength(); i++) {
			Option option = new Option(options.getItem(i));
			listOptions.add(i, option);
		}

		return listOptions;
	}

	public OptionElement getOption() {
		return selectElement.getOptions().getItem(selectElement.getSelectedIndex());
	}

	public boolean isSelect() {
		if (selectElement.getSelectedIndex() >= 0) {
			return true;
		}
		return false;
	}

	public HandlerRegistration addClickHandler(ClickHandler handler) {
		return addDomHandler(handler, ClickEvent.getType());
	}

}
